package com.sychip.fhc.app.todo.nav.tab


//import com.sychip.fhc.app.todo.nav.tab.screen.BleScannerScreen
//import com.sychip.fhc.app.todo.nav.tab.screen.PullListScreen
//import com.sychip.fhc.app.todo.nav.tab.screen.devicesetting.BleDeviceSettingScreen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.KeyboardCommandKey
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalDensity
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.fhc.base.BackHandler
import com.fhc.view.BottomBarBox
import com.fhc.view.StatusBarBox
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.sychip.fhc.app.drawer.screen.CanvasScreen
import com.sychip.fhc.app.drawer.screen.DialogSampleScreen
import com.sychip.fhc.app.drawer.screen.PullListScreen
import com.sychip.fhc.app.drawer.screen.SettingsScreen
import com.sychip.fhc.app.drawer.screen.components.ComponentsScreen
import timber.log.Timber

enum class Screen {
    Home,
    Dialog,
    PullList,
    Settings,
    Components,
    Canvas
}

const val NAV_JSON_ARG = "navJsonArg"
data class Post(val id: Int,val title: String,val content: String)
const val PullList_BleSetting_SCREEN = "PullList_BleSetting"
const val PullList_BleSetting_Route ="$PullList_BleSetting_SCREEN?${NAV_JSON_ARG}={$NAV_JSON_ARG}" //一个必须一个option

sealed class NavigationItem(val route: String, val label: String, val icon: ImageVector) {
    data object Home : NavigationItem(
        Screen.Home.name,
        "Home",
        Icons.Default.Home
    )
    data object Dialog : NavigationItem(
        Screen.Dialog.name,
        "Dialog",
        Icons.Default.Person)
    data object PullList : NavigationItem(
        Screen.PullList.name,
        "PullList",
        Icons.AutoMirrored.Default.List)
    data object Setting : NavigationItem(
        Screen.Settings.name,
        "Settings",
        Icons.Default.Settings)
    data object Components : NavigationItem(
        Screen.Components.name,
        "组件",
        Icons.Default.KeyboardCommandKey)
    data object Canvas : NavigationItem(
        Screen.Canvas.name,
        "Canvas",
        Icons.Default.KeyboardCommandKey)

}

class AppTabNavigationActions(private val navController: NavHostController) {
    fun navigateToBleSetting(param: Post? = null) {

        val moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
        val jsonAdapter = moshi.adapter(Post::class.java).lenient()
        val json = jsonAdapter.toJson(param)
        //PullList_BleSetting/TTTTT
        //PullList_BleSetting/TTTTT?devId=123
        var route = PullList_BleSetting_SCREEN
        if(param != null){
            route = "$route?${NAV_JSON_ARG}=$json"
        }

        Timber.i("   BleSetting_ROUTE   route:%s", route)
        navController.navigate( route = route )
    }
}
private val StartRoute = NavigationItem.Home.route
var currentRoute = StartRoute
@Composable
fun BottomNavigationBar(navController: NavController) {
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    var currentRoute = navBackStackEntry?.destination?.route

    val items = listOf(
        NavigationItem.Home,
        NavigationItem.Dialog,
        NavigationItem.PullList,
        NavigationItem.Setting,
        NavigationItem.Components,
        NavigationItem.Canvas,
    )
//    val modifier = Modifier.height(84.dp) // 自定义高度
    //小米手机，containerColor设置不起作用，模拟器时可以的；
//    containerColor = Color.DarkGray,
//    contentColor = Color.Black,

    NavigationBar() {
        items.forEach { item ->
            NavigationBarItem(
                icon = {
                    Icon(
                        imageVector = item.icon,
                        contentDescription = null
                    )
                },
                label = { Text (item.label) },
                onClick = {
                    if(item.route != currentRoute) {
                        navController.navigate(item.route) {
                            popUpTo(navController.graph.startDestinationId)
                            launchSingleTop = true
                        }
                    }else{
                        currentRoute = item.route
                    }
                },
                selected = currentRoute == item.route,
            )
        }
    }
}


@Composable
fun MainTabNavHost(
    modifier: Modifier = Modifier,
    navController: NavHostController = rememberNavController(),
    viewModel:MainTabViewModel = hiltViewModel(),
    onBack: () -> Unit
) {
    val density = LocalDensity.current
//    val statusBarHeight = WindowInsets.statusBars.getTop(density).
//    val navigatorBarHeight = WindowInsets.navigationBars.getBottom(density).pxToDp(density)

    val navActions: AppTabNavigationActions = remember(navController) {AppTabNavigationActions(navController)}
    val tabStateFlow by viewModel.tabStateFlow.collectAsStateWithLifecycle()
//   val window:Window = (LocalContext.current as Activity).window
//    window.navigationBarColor = R.color.errorColor
    Timber.i("   currentRoute  :%s", currentRoute)
    Scaffold(
        modifier = modifier.fillMaxSize().background(Color.Red),
//            .statusBarsPadding()
//            .navigationBarsPadding(),

        contentWindowInsets = WindowInsets(0, 0, 0, 0),
        topBar = {
        },
        bottomBar = {
            if(tabStateFlow.showBottomNavbar) BottomNavigationBar(navController)
        },
    ) { innerPadding ->
        innerPadding.calculateTopPadding()
        BackHandler(onBack = onBack)
        NavHost(
            navController = navController,
            startDestination = StartRoute,
            modifier = Modifier.padding(innerPadding),
            //.consumeWindowInsets(innerPadding)
        ) {
            composable(NavigationItem.Home.route) {
                Column {
//                    val UUID_SERVICE_DEVICE: UUID = UUID.fromString("00001523-1212-efde-1523-785feabcd123")
//                    val uuid = ParcelUuid(UUID_SERVICE_DEVICE)
//                    val filters = listOf(
////                        WithServiceUuid("AICamera", uuid, true),
////                        OnlyNearby(rssi = -50 /* dBm */, initiallySelected = false),
////                        OnlyWithNames(initiallySelected = true),
//                        CustomFilter("AICamera", true) { isFilterSelected, result ->
//                            !isFilterSelected || result.device.name?.contains("AICamera", ignoreCase = true) == true
//                        }
//                    )
//                    ScannerScreen(
//                        filters = filters,
//                        cancellable = true,
//                        onResult = { it->
//                            when (it) {
//                                is DeviceSelected -> {
////                                    navigationViewModel.navigateTo(BlinkyDestinationId, it.scanResults.device)
//                                }
//                                ScanningCancelled -> {
//
//                                }
//                            }
//                        }
//                    )

//                    BleScannerScreen(
//                        cancellable = true,
//                    )
                }
            }
            composable(NavigationItem.Dialog.route) {
                Column (  modifier = modifier.fillMaxSize().navigationBarsPadding()){//.statusBarsPadding().navigationBarsPadding()
                    Text(text = "aaa",modifier = Modifier.fillMaxWidth().background(Color.Red))
                    DialogSampleScreen()
                }
            }
            composable(NavigationItem.PullList.route) {
                Column (Modifier.fillMaxSize()){
                    PullListScreen(viewModel = hiltViewModel())
                }
            }
            composable(NavigationItem.Setting.route) {
                Column (Modifier.fillMaxSize()){
                    SettingsScreen(viewModel = hiltViewModel(),)
                }
            }
            composable(NavigationItem.Components.route) {
                Column (Modifier.fillMaxSize()){
                    ComponentsScreen(viewModel = hiltViewModel(),)
                }
            }
            composable(NavigationItem.Canvas.route) {
                Column (Modifier.fillMaxSize()){
                    CanvasScreen(viewModel = hiltViewModel(),)
                }
            }

            composable(
                PullList_BleSetting_Route,
                arguments = listOf(
                    navArgument(NAV_JSON_ARG) { type = NavType.StringType; nullable = true },
                )
            ) { entry ->
                val navJsonArg = entry.arguments?.getString(NAV_JSON_ARG)

                val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
                val jsonAdapter = moshi.adapter(Post::class.java).lenient()
                val serviceObject = navJsonArg?.let { it1 -> jsonAdapter.fromJson(it1) }

                Timber.i("  navJsonArg:%s %s  %s",  navJsonArg, serviceObject?.title,
                    serviceObject?.id
                )
                Surface {
                    Column(modifier = Modifier.fillMaxSize()) {
                        StatusBarBox()
//                        BleDeviceSettingScreen(
//                            onTaskUpdate = {
//                            },
//                            onBack = { navController.popBackStack() }
//                        )
                        BottomBarBox()
                    }
                }
            }
        }
    }
}